package com.zhj.jvm.test;

/**
 * @author zhj
 */
public class Singleton {

    private static volatile Singleton instance;
    private static boolean flag  = true;

    private Singleton() {
        if (flag) {
           synchronized (Singleton.class) {
               if (flag) {
                   flag = false;
               }
           }
        } else {
            throw new RuntimeException("试图破坏单例！");
        }
    }

    public Singleton getInstance() {
        // 双重检测锁
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}
